package com.cygsunri.report.service.mediator;


import com.cygsunri.report.entity.GeneralReport;
import com.cygsunri.scada.base.BasePSR;
import com.cygsunri.scada.service.ScadaPSRService;
import com.google.common.base.Strings;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 特殊字符串替换的中介器,特殊字符串包含在一个大括号内
 */
@Component
public class ConstStringMediator extends AbstractReportMediator {
    private static final String SUBSTATION = "{substation}"; //子站名称
    private static final String DATE = "{date}"; //日期
    private static final String MAKE_DATE = "{makeDate}"; //制表日期
    private static final String END_DATE = "{endDate}"; //结束日期

    @Autowired
    private ScadaPSRService scadaPSRService;

    @Override
    protected int mediateInner(GeneralReport report, Workbook workbook) {
        for (Sheet sheet : workbook) {
            for (Row row : sheet) {
                for (Cell cell : row) {
                    logger.info("单元格类型: {}", cell.getCellType());

                    if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
                        String context = cell.getStringCellValue();

                        if (context.contains(SUBSTATION) && !Strings.isNullOrEmpty(report.getSubstation())) {
                            BasePSR substation = scadaPSRService.getDeviceByPsrId(report.getSubstation());

                            if (substation != null) {
                                context = context.replace(SUBSTATION, substation.getName());
                            }
                        }

                        if (context.contains(DATE)) {
                            context = context.replace(DATE, report.getDate());
                        }

                        if (context.contains(MAKE_DATE)) {
                            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                            context = context.replace(MAKE_DATE, simpleDateFormat.format(new Date()));
                        }

                        if (context.contains(END_DATE)) {
                            context = context.replace(END_DATE, report.getEndDate());
                        }

                        cell.setCellValue(context);
                    }
                }
            }
        }

        return 0;
    }
}
